<template>
  <el-dialog v-model="visible" title="重置密码" width="500">
    <el-form :model="form" ref="formRef" labelWidth="100px">
      <el-form-item
        label="新密码"
        prop="password"
        :rules="[
          {
            required: true,
            message: '请输入新密码',
            trigger: 'blur',
          },
        ]"
      >
        <el-input
          v-model.trim="form.password"
          placeholder="请输入新密码"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item
        label="确认新密码"
        prop="newPassword"
        :rules="[
          {
            required: true,
            message: '请输入确认新密码',
            trigger: 'blur',
          },
          {
            required: true,
            validator: validatePass,
            trigger: 'blur',
          },
        ]"
      >
        <el-input
          v-model.trim="form.newPassword"
          placeholder="请输入确认新密码"
          autocomplete="off"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm"> 确定 </el-button>
        <el-button @click="onCancel">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import api from "@/api/pwd.js";
const props = defineProps({
  typeName: { type: String, default: "新增" },
});
const visible = ref(false);
const emits = defineEmits(["success", "error"]);
const formRef = ref();
const form = ref({
  password: "",
  newPassword: "",
});
const validatePass = (rule, value, callback) => {
  if (form.value.password === form.value.newPassword) {
    callback();
  } else {
    callback(new Error("新密码与确认新密码不一致"));
  }
};
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const res = await api.reset(form.value);
      if (res.data) {
        ElMessage.success(res.msg || `保存成功！`);
        onCancel();
        emits("success");
      } else {
        ElMessage.error(res.msg || `保存失败！`);
        emits("error");
      }
    }
  });
};

const onCancel = () => {
  formRef.value.clearValidate();
  visible.value = false;
};
const openDialog = (row) => {
  visible.value = true;
  form.value = row ? JSON.parse(JSON.stringify(row)) : {};
};

defineExpose({
  openDialog,
});
</script>
